package com.jzo2o.trade.Strategy.PayStrategyImpl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.jzo2o.api.trade.dto.response.PayResDTO;
import com.jzo2o.api.trade.enums.PayTypeEnum;
import com.jzo2o.trade.Strategy.PayStrategy;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.IAliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * \* User: chy
 * \* Date: 2025/10/10  14:16
 * \* Description:
 * \
 */
@Service("1") // 支付宝支付 todo:这里注意, 枚举的code是Integer,而数据库的trading_type是String,所以需要转换一下.
@Slf4j
public class AliPayServiceImpl implements PayStrategy {

    @Autowired
    private Config aliPayConfig;
    /**
     * 支付
     *
     * @param trading
     * @return
     */
    @Override
    public PayResDTO pay(Trading trading) {
        log.info("支付宝支付开始");
        PayResDTO resDTO = null;
        // 1.判断支付类型
        if (PayTypeEnum.NATIVE.getValue().equals(trading.getTradingType())) {
            resDTO = nativePay(trading);
            return resDTO;
        }
        return null;
    }
    /**
     * 支付宝面对面扫码支付
     *
     * @param trading
     * @return
     */
    private PayResDTO nativePay(Trading trading) {
        try {
            // 设置支付宝参数
            Factory.setOptions(aliPayConfig);
            // 1.创建支付服务
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                    .preCreate(trading.getMemo(), trading.getTradingOrderNo(), trading.getTradingAmount()+"");
            log.info("支付宝支付结果:{}", JSONUtil.toJsonStr( response));

            // 2.拿到二维码url
            String qrCode = response.qrCode;
            QrConfig qrConfig = new QrConfig();
            String base64Img = QrCodeUtil.generateAsBase64(qrCode, qrConfig, ImgUtil.IMAGE_TYPE_JPG);

            // 3.构建返回对象
            PayResDTO resDTO = new PayResDTO();
            resDTO.setPlaceOrderMsg(response.msg);
            resDTO.setQrCode(base64Img);
            resDTO.setPayOrderNo(Long.parseLong(trading.getTradingOrderNo()));
            return resDTO;
        } catch (Exception e) {
            log.error("支付宝支付异常:{}", e.getMessage());
        }
        return null;
    }
}
